package com.hellogood.yaohuo.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.shared.entity.Color;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class ColorDAO extends DBHelper {
	Logger log = Logger.getLogger(this.getClass());
	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Color> colorList = new ArrayList<Color>();
		if (rs != null) {
			while (rs.next()) {
				Color c = new Color();
				c.setColorCode(rs.getString("ColorCode"));
				c.setColorName(rs.getString("ColorName"));
				colorList.add(c);
			}
		}
		return colorList;
	}

	@SuppressWarnings("unchecked")
	public List<Color> getAllColor() {
		String sql = "SELECT * FROM COLOR ORDER BY COLORCODE";
		List<?> colorList = super.query(sql);
		return (List<Color>) colorList;
	}

	public String addNewColor(Color c) {
		String sql = "INSERT INTO COLOR(COLORCODE,COLORNAME) VALUES('" + c.getColorCode() + "','" + c.getColorName() + "')";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return e.getMessage();
		}
		return "";
	}

	public String removeColor(String colorCode) {
		String sql = "DELETE FROM COLOR WHERE COLORCODE = '" + colorCode + "'";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return e.getMessage();
		}
		return "";
	}

	public Color getColorByCode(String code) {
		String sql = "SELECT * FROM COLOR WHERE COLORCODE = '" + code + "'";
		List<?> colorList = super.query(sql);
		if (colorList == null || colorList.isEmpty()) {
			return null;
		}
		return (Color) colorList.get(0);
	}
	
	public Color getColorByName(String name) {
		String sql = "SELECT * FROM COLOR WHERE ColorName = '" + name + "'";
		List<?> colorList = super.query(sql);
		if (colorList == null || colorList.isEmpty()) {
			return null;
		}
		return (Color) colorList.get(0);
	}
}
